package org.opensuse.bs.ui.actions;

import java.io.File;
import java.util.Vector;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.opensuse.bs.ui.OSC;

public class UpdateAction implements IObjectActionDelegate {
	private IResource[] selected;
	
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
	}
	
	public void run(IAction action) {
		for(IResource r : selected) {
			final IContainer container = (IContainer) r;
			WorkspaceJob job = new WorkspaceJob("Updating Projects") {
				public IStatus runInWorkspace(IProgressMonitor monitor) {
					try {
						File dir = new File(container.getLocation().toOSString());
						Vector<String> result = OSC.run("up", null, dir);
						if(result.isEmpty()) {
							return Status.CANCEL_STATUS;
						}
						container.refreshLocal(IResource.DEPTH_INFINITE, monitor);
					}catch(Exception e) {
						e.printStackTrace();
					}
					return Status.OK_STATUS;
				}
			};
			job.schedule();
		}
	}
	
	public void selectionChanged(IAction action, ISelection selection) {
		if(selection instanceof ITreeSelection) {
			TreePath[] paths = ((ITreeSelection) selection).getPaths();
			if(paths.length != 0) {
				selected = new IResource[paths.length];
				for(int i=0;i<paths.length;i++) {
					selected[i] = (IResource) paths[i].getLastSegment();
				}
			}
			else {
				selected = new IResource[0];
			}
		}
	}

}
